from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, DateTime, Boolean, TIMESTAMP, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from run import config


def get_mysql_conn_url(config):
    mysql_conn_map = dict(
        dialect="mysql",
        driver="pymysql",
        host=config.get('database', "MYSQL_HOST"),
        port=config.get('database', "MYSQL_PORT"),
        database=config.get('database', "MYSQL_DB"),
        user=config.get('database', "MYSQL_USER"),
        password=config.get('database', "MYSQL_PASSWORD"),
    )
    url = "{dialect}+{driver}://{user}:{password}\
@{host}:{port}/{database}?charset=utf8".format(**mysql_conn_map)
    return url


engine = create_engine(get_mysql_conn_url(config), echo=True)
metadata = MetaData(engine)

Base = declarative_base()
DBsession = sessionmaker(bind=engine)
session = DBsession()


def close():
    session.commit()
    session.close()
